# -*-encoding:utf-8 -*-
import json
import time

import requests


class AccessToken(object):
    # 微信公众测试号账号
    APPID = "wx5a3bcb0118012354"
    # 微信公众测试号密钥
    APPSECRET = "d00992d7d0ad0a4d337a96ade90caeeb"

    def __init__(self, app_id=APPID, app_secret=APPSECRET) -> None:
        self.app_id = app_id
        self.app_secret = app_secret

    def get_access_token(self) -> str:
        """
        获取access_token凭证
        :return: access_token
        """
        url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={self.app_id}&secret={self.app_secret}"
        resp = requests.get(url)
        result = resp.json()
        if 'access_token' in result:
            return result["access_token"]
        else:
            print(result)


class SendMessage(object):
    # 消息模板id
    TEMPLATE_ID = 'kubdqh7PDzFerFyp53cyU48LL4YeYVMOhXpfzO_UziY'
    # 点击跳转链接
    CLICK_URL = ''

    def __init__(self, template_id=TEMPLATE_ID, click_url=CLICK_URL) -> None:
        """
        构造函数
        :param template_id: 消息模板id
        :param click_url: 点击跳转链接
        """
        self.access_token = AccessToken().get_access_token()
        self.template_id = template_id
        self.click_url = click_url

    def get_type_and_data(self, type_message):
        if type_message == 'warning':  # 警告消息
            self.template_id = "jzimcAdBdrYvK9F2vtDNnuHkO3eyABpm7Y6TjQ03XL0"
        elif type_message == 'start':  # 所有进程已启动
            # print("服务启动,设备已上线!")
            self.template_id = "TLDZAUXFNmKtBEth6FSJQfAj3s3Vr0tmQGJChOMJbAE"
        elif type_message == 'low_power':  # 低电量
            self.template_id = "iwe9v-gAQZt0wdTV5GsyB_C_vURHfsHHFwCkSjfxIFE"
        elif type_message == 'local_failure':  # 出于未知原因，定位失败
            pass
        elif type_message == 'longtime_not_move':  # 位置超时未移动(50m)
            pass
        elif type_message == 'ssh':  # ssh远程登陆
            # print("SSH远程访问启动!")
            self.template_id = "I9qvgbgPMORo1wuV1Yie4ymZCuoE3njhh9l2CEbopME"
        elif type_message == 'downline':  # 设备离线
            self.template_id = "9zOuMnw0nHXdxIadx7VUGY7B4mV1YFTYp6hTSkBdy0I"

    def get_send_data(self, json_data, users) -> object:
        date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        """
        获取发送消息data
        :param json_data: json数据对应模板
        :return: 发送的消息体
        """

        return {
            "touser": users,
            "template_id": self.template_id,
            "url": self.click_url,
            "topcolor": "#FF0000",
            # json数据对应模板
            "data": {
                "title": {
                    "value": json_data["title"],
                    # 字体颜色
                    "color": "#173177"
                },
                "content": {
                    "value": json_data["content"],
                    "color": "#173177"
                },
                "time": {
                    "value": date,
                    "color": "#000000"
                }
            }
        }

    def send_message(self, json_data) -> None:
        """
        发送消息
        :param json_data: json数据
        :return:
        """
        # 模板消息请求地址
        users = ['of0h_6aONSuQyNyUTAk8myTuDu0A']  # , 'of0h_6eFlxAQbzlqqMUvbu6uViVo']  # 消息接受对象，默认群发送，即所有对象

        if "key" in json_data:
            users.clear()
            print("单条消息发送.")
            users.append(json_data["key"])

        for i in range(len(users)):
            url = f"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={self.access_token}"
            data = json.dumps(self.get_send_data(json_data, users[i]))
            resp = requests.post(url, data=data)
            result = resp.json()
            if result["errcode"] == 0:
                print("第{}条消息发送成功,对象{}\n".format(i, users[i]))
            else:
                print(result)


class Main(object):
    def __init__(self) -> None:
        """
        构造函数
        """
        pass

    def main(self, type_message, content, users) -> None:
        # 实例SendMessage
        sm = SendMessage()
        sm.get_type_and_data(type_message)
        # 获取接口返回数据
        content = content.split('&')
        if users == "all":
            json_data = {"title": "{}".format(content[0]), "content": "{}".format(content[1])}
        else:
            json_data = {"title": "{}".format(content[0]), "content": "{}".format(content[1]),
                         "key": "{}".format(users)}
        # 发送消息
        sm.send_message(json_data=json_data)


push_message = Main()
# push_message.main("warning", "位置预警！&当前正处于预警范围内！", "all")
